﻿/*
    RaonWebClient : 반복되는 WebClient 설정 코드들을 줄이기 위한 WebClient
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;

namespace TodayHumor
{
    public class RaonWebClient : WebClient
    {
        public CookieContainer CookieContainer = App.Cookies;

        [SecuritySafeCritical]
        public RaonWebClient()
        {
            // 오늘의 유머 사이트는 euc-kr 인코딩을 사용하기 때문에
            this.Encoding = new Korean.Text.Encoding.EuckrEncoding();

            // nginx에서 Accept-Language 속성을 안 주면 Internal Server Error를 뿌리기 때문에
            this.Headers["Accept-Language"] = "ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4";
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest r = base.GetWebRequest(address);
            var request = r as HttpWebRequest;
            if (request != null)
            {
                request.CookieContainer = CookieContainer;
            }
            return r;
        }

        protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
        {
            WebResponse response = base.GetWebResponse(request, result);
            ReadCookies(response);
            return response;
        }

        private void ReadCookies(WebResponse r)
        {
            var response = r as HttpWebResponse;
            if (response != null)
            {
                CookieCollection cookies = response.Cookies;
                CookieContainer.Add(response.ResponseUri, cookies);
            }
        }
    }
}
